<?php
namespace app\index\controller;
use app\index\model\Image;
use think\Cache;

class User extends Base
{
    /**
     * 用户查看个人信息
     */
    public function lookMsg()
    {
        $data = input('post.');

        if (!isset($data['us_id']) || empty($data['us_id'])) {
            $info['code']    = '400';
            $info['message'] = '非法请求';
            echo displayJson($info);die;
        }

        //查询用户信息
        $res = db('user',[],false)->where('us_id',$data['us_id'])->where('us_status','1')->find();

        $res['us_days'] = ceil((time() - $res['us_create_time'])/60/60/24); //入驻天数

        unset($res['us_password']);
        unset($res['us_status']);

        if ($res) {
            $info['code']    = '200';
            $info['data']    = $res;
            echo displayJson($info);die;
        } else {
            $info['code']    = '400';
            $info['message'] = '服务器错误';
            echo displayJson($info);die;
        }
    }

    /**
     * 用户完善信息
     */
    public function perfectMsg()
    {
        $data = input('post.');

        //校验数据
        $validate = \think\Loader::validate('User');
        if(!$validate->check($data)){
            $info = array('code' => '400','message'=>$validate->getError());
            echo displayJson($info);die;
        }

        if (!plum_is_phone($data['us_phone'])) {
            $info['code']    = '400';
            $info['message'] = '手机号格式不正确';
            echo displayJson($info);die;
        }

        $data['us_username'] = htmlspecialchars($data['us_username']);
        $data['us_wx']       = htmlspecialchars($data['us_wx']);
        $data['us_desc']     = htmlspecialchars($data['us_desc']);


        //修改数据库
        $res = db('user',[],false)->where('us_id',$data['us_id'])->update($data);

        if ($res >= 0) {

            //修改留言表里的用户昵称和头像信息
            $set['ly_uname']  = $data['us_username'];

            db('liuyan',[],false)->where('ly_uid',$data['us_id'])->update($set);

            //修改商品表里的学校信息
            $setGoods['gd_school'] = $data['us_school'];
            db('goods',[],false)->where('gd_uid',$data['us_id'])->update($setGoods);

            $info['code']    = '200';
            $info['message'] = '保存成功';
            echo displayJson($info);die;
        } else {
            $info['code']    = '400';
            $info['message'] = '保存失败';
            echo displayJson($info);die;
        }
    }

    /**
     * 修改头像
     */
    public function updateImage()
    {
        $id =input('id');

        if (!isset($id) || empty($id)) {
            $info['code']    = '401';
            $info['message'] = '用户信息缺失';
            echo displayJson($info);die;
        } else {
            $row = db('user',[],false)->where('us_id',$id)->find();

            $stream  = input('us_image');
            $tmpName = uploadBase64($stream); //将流文件保存为临时文件
            $suffix  = getSuffix($tmpName);  //获取后缀名

            if ($suffix !== false) {
                $realName = $row['us_email'].'_'.time().'_'.rand(00,99).'.'.$suffix;
                $ret      = rename($tmpName,$realName);

                if ($ret) {
                    //压缩图片
                    $source =  $realName;//原图片名称
                    $dst_img = './image/head/'.$realName;//压缩后图片的名称
                    @(new Image($source))->compressImg($dst_img);

                    @unlink($realName);

                    //如果不等于默认头像就删除原来的图片
                    if ($row['us_image'] !== 'http://www.taoerhuo.top/bishe/public/image/index/default.png') {
                        $delUrl = explode('/', $row['us_image']);
                        $delStr = end($delUrl);

                        @unlink('./image/head/'.$delStr);
                    }

                    //更新数据库
                    $new_dst_img      = substr($dst_img, 1);
                    $data['us_image'] = 'http://www.taoerhuo.top/bishe/public'.$new_dst_img;

                    $res = db('user',[],false)->where('us_id',$id)->update($data);
                    if ($res >= 0) {

                        //修改留言表里的用户昵称和头像信息
                        $set['ly_uimage']  = $data['us_image'];

                        db('liuyan',[],false)->where('ly_uid',$id)->update($set);

                        
                        $info['code']    = '200';
                        $info['message'] = '头像保存成功';
                        $info['url']     = $data['us_image'];
                        echo displayJson($info);die;
                    } else {
                        $info['code']    = '400';
                        $info['message'] = '上传失败';
                        echo displayJson($info);die;
                    }
                } else {
                    $info['code']    = '400';
                    $info['message'] = '头像获取失败';
                    echo displayJson($info);die;
                }
            }
        }

    }

    /**
     * 加入我们
     */
    public function joinUs()
    {
        $data = input('post.');

        //校验数据
        $validate = \think\Loader::validate('Join');
        if(!$validate->check($data)){
            $info = array('code' => '400','message'=>$validate->getError());
            echo displayJson($info);die;
        }

        if (empty($data['a_qq']) && empty($data['a_phone'])) {
            $info['code']    = '400';
            $info['message'] = '请至少留下一种联系方式';
            echo displayJson($info);die;
        }

        $data['a_name']  = htmlspecialchars($data['a_name']);
        $data['a_major'] = htmlspecialchars($data['a_major']);
        $data['a_desc']  = htmlspecialchars($data['a_desc']);

        $data['a_create_time'] = time();

        //插入数据库
        $res = db('apply',[],false)->insert($data);

        if ($res) {
            $info['code']    = '200';
            $info['message'] = '提交成功';
            echo displayJson($info);die;
        } else {
            $info['code']    = '400';
            $info['message'] = '提交失败';
            echo displayJson($info);die;
        }
    }

    /**
     * 意见反馈
     */
    public function opinion()
    {
        $data = input('post.');

        if (empty($data['uid'])) {
            $info['code']    = '401';
            $info['message'] = '用户id缺失';
            echo displayJson($info);die;
        }

        if (empty($data['content'])) {
            $info['code']    = '400';
            $info['message'] = '内容不能为空';
            echo displayJson($info);die;
        }

        $insert['on_uid']          = $data['uid'];
        $insert['on_content']     = htmlspecialchars($data['content']);
        $insert['on_create_time'] = time();

        $res = db('opinion',[],false)->insert($insert);

        if ($res) {
            $info['code']    = '200';
            $info['message'] = '提交成功！感谢您的反馈，我们会认真处理！';
            echo displayJson($info);die;
        } else {
            $info['code']    = '400';
            $info['message'] = '抱歉，系统出错，提交失败。';
            echo displayJson($info);die;
        }
    }

    /**
     * 修改密码 - 发送邮箱验证码
     */
    public function sendEmail()
    {
        $email = input('email');

        if (!$email) {
            $info['code']    = '400';
            $info['message'] = '参数丢失';
            echo displayJson($info);die;
        }

        $code = make_Verification_Code(6);
        $send_data = array(
            'to_email'   => $email,
            'content'    =>'【淘二货】您正在进行修改密码操作，本次操作验证码：<span style="font-size: 20px;font-weight: bold;"> '.$code.' </span>，请在10分钟内完成验证<br/>如有疑问，请联系管理员QQ：1298025852'
        );

        $send      = sendEmail($send_data);

        if (!$send) {
            $info['code']    = '400';
            $info['message'] = '邮件发送失败';
            echo displayJson($info);die;
        } else {
            $check_code = explode(' ',$send_data['content']);

            // 设置redis
            $options = ['type'  => 'Redis']; //指定类型
            Cache::init($options);//初始化
            Cache::set($email,$check_code['4'],600); //redis key有效期为10分钟

            $info['code']         = '200';
            $info['message']      = '邮件发送成功';
            echo displayJson($info);die;
        }

    }

    /**
     * 执行修改密码
     */
    public function queryEditPwd()
    {
        $code   = input('code');
        $uid    = input('uid');
        $oldPwd = input('oldPwd');
        $newPwd = input('newPwd');
        
        if (!$code || !$oldPwd || !$newPwd || !$uid) {
            $info['code']         = '400';
            $info['message']      = '参数丢失';
            echo displayJson($info);die;
        }

        $row = db('user',[],false)->where('us_id',$uid)->where('us_status',1)->find();

        if (!$row) {
            $info['code']         = '401';
            $info['message']      = '用户信息异常，请重新登录';
            echo displayJson($info);die;
        }

        $checkCode = Cache::get($row['us_email']);

        if (!$checkCode) {
            $info['code']    = 400;
            $info['message'] = '验证码错误';
            echo displayJson($info);die;
        }

        if (trim($code) !== $checkCode) {
            $info['code']    = '400';
            $info['message'] = '验证码错误';
            echo displayJson($info);die;
        }

        $oldPwd = md5($oldPwd.'SecretIndex');
        if ($oldPwd !== $row['us_password']) {
            $info['code']    = '400';
            $info['message'] = '原密码错误';
            echo displayJson($info);die;
        }

        //执行修改
        $set['us_password'] = md5($newPwd.'SecretIndex');
        $res = db('user',[],false)->where('us_id',$uid)->update($set);

        if ($res) {
            //删除Redis数据
            Cache::rm($row['us_email']);

            $info['code']    = '200';
            $info['message'] = '修改成功';
            echo displayJson($info);die;
        } else {
            $info['code']    = '400';
            $info['message'] = '修改失败';
            echo displayJson($info);die;
        }

    }

}